import Realm from 'realm'
import { RECLAIM_USER_MESSAGE } from '../store/reducer/message'

const FriendSchema = {
  name: 'Friend',
  primaryKey: 'fid',
  properties: {
    uid: {type: 'int', indexed: true},
    fid: {type: 'int', indexed: true},
    fname: {type: 'string'},
    currentChatBg: "string",
    bgWall: {type: 'string', optional: true},
    address: {type: 'string', optional: true},
    avatar: {type: 'string'},
    email: {type: 'string'},
    mobile: {type: 'string', optional: true},
    motto: {type: 'string', optional: true},
    gender: {type: 'bool',default: false},
    isDisturb: {type: 'bool', default: false},
    jurisdiction: {type: 'int'},
    label: {type: 'string', optional: true},
    moments: {type: 'int'},
    remarks: {type: 'string', optional: true}
  }
}

const UserFriendSchema = {
  name: 'UserFriend',
  primaryKey: 'uid',
  properties: {
    uid: {type: 'int', indexed: true},
    data: {type: 'string'}
  }
}


const MessageSchema = {
  name: 'Message',
  primaryKey: 'hash',
  properties: {
    uid: { type: 'int', indexed: true },
    fid: { type: 'int', indexed: true },
    hash: { type: 'string', indexed: true },
    dist_type: { type: 'string' },
    content_type: { type: 'string' },
    content: { type: 'string' },
    create_time: { type: 'date' },
    is_received: { type: 'bool', optional: true },
    is_sent: { type: 'bool', optional: true },
    status: { type: 'int', optional: true },
    is_owner: { type: 'bool', default: false },
  },
}

const RecentMessageSchema = {
  name: 'RecentMessage',
  primaryKey: 'uid',
  properties: {
    uid: {type: 'int', indexed: true},
    data: {type: 'string'}
  }
}

export default class Storage {

  schema = [FriendSchema, UserFriendSchema, MessageSchema, RecentMessageSchema]
  version = 7

  constructor() {
    this.init()
  }
  close() {
    this.realm.close()
  }

  async init() {
    if(!this.realm||this.realm.isClosed) {
      this.realm = await Realm.open({schema: this.schema, schemaVersion: this.version})
    }
  }
  deleteAll() {
    return this.query((realm) => {
      realm.deleteAll()
    })
  }

  async query(realm) {
    await this.init()
    return new Promise((resolve, reject) => {
      this.realm.write(async () => {
        try {
          const res = await realm(this.realm)
          resolve(res)
        }catch(error){
          reject(error)
        }
      })
    })
  }
}
